package gl.android.biyiqing.bean;

import gl.android.biyiqing.R;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

public class BYQUserInfo {
	// gender 1 man 2:woman
	public static String XUELI = "学历";
	public static String JUZHUQINGKUANG = "居住情况";
	public static String HUNYINZHUNGKUANG = "婚姻状况";
	public static String ZHIYE = "职业";
	public static String GERENZICHANG = "个人资产";
	public static String GOUCHEQINGKUANG = "购车情况";
	public static String GEXING = "个性";
	public static String XINGQU = "兴趣爱好";
	public static String MINZU = "民族";
	public static String AVATAR = "形象照";
	public static String XINGZUO = "星座";
	public static String JIGUAN = "籍贯";
	public static String QUYU = "区域";
	final static String filename = "/lovep.txt";
	final static String filename2 = "/lovea.txt";
	final static String filename3 = "/lovejg.txt";
	static {
		try {
			readResouceFile(filename);
			readShengShiFile(filename3);
			readHuBeiFile(filename2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static JSONArray shenfenJSON;
	private static JSONArray HuBeiQuYuJSON;

	public static JSONArray getShenfenJSON() {
		if (shenfenJSON == null) {
			try {
				readShengShiFile(filename3);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return shenfenJSON;
	}

	public static JSONArray getHubeiQuYuJSON() {
		if (HuBeiQuYuJSON == null) {
			try {
				readHuBeiFile(filename2);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				HuBeiQuYuJSON = null;
			}
		}
		return HuBeiQuYuJSON;
	}

	private static void readShengShiFile(final String filename)
			throws FileNotFoundException, IOException, JSONException {
		if (shenfenJSON == null) {
//			System.out.println("readShengShiFile");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					BYQUserInfo.class.getResourceAsStream(filename)));
			StringBuilder sb = new StringBuilder();
			String readedLine = br.readLine();
			while (readedLine != null) {
				sb.append(readedLine);
				readedLine = br.readLine();
			}
			br.close();
			JSONObject jo = new JSONObject(sb.toString());
			final JSONArray jsonArray = jo.getJSONArray("data");
			shenfenJSON = new JSONArray();
			for (int i = 0; i < jsonArray.length(); i++) {
				int depth = jsonArray.getJSONObject(i).getInt("depth");
				if (depth == 0) {
					JSONObject shen = new JSONObject();
					shen.put("id", jsonArray.getJSONObject(i).getInt("areaid"));
					shen.put("name",
							jsonArray.getJSONObject(i).getString("areaname"));
					shen.put("childs", new JSONArray());
					shenfenJSON.put(shen);
				}
			}
			for (int i = 0; i < jsonArray.length(); i++) {
				int depth = jsonArray.getJSONObject(i).getInt("depth");
				if (depth == 1) {
					JSONObject xian = new JSONObject();
					xian.put("id", jsonArray.getJSONObject(i).getInt("areaid"));
					xian.put("name",
							jsonArray.getJSONObject(i).getString("areaname"));

					for (int j = 0; j < shenfenJSON.length(); j++) {
						if (shenfenJSON.getJSONObject(j).getInt("id") == jsonArray
								.getJSONObject(i).getInt("rootid")) {
							shenfenJSON.getJSONObject(j).getJSONArray("childs")
									.put(xian);
						}
					}
				}
			}
		}
	}

	private static void readHuBeiFile(String filename) throws Exception,
			JSONException {
//		System.out.println("readHuBeiFile:" + filename);
		if (HuBeiQuYuJSON == null) {
			final InputStream resourceAsStream = BYQUserInfo.class
					.getResourceAsStream(new String(filename));
			if (resourceAsStream == null) {
				HuBeiQuYuJSON = null;
				return;
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(
					resourceAsStream));
			StringBuilder sb = new StringBuilder();
			String readedLine = br.readLine();
			while (readedLine != null) {
				sb.append(readedLine);
				readedLine = br.readLine();
			}
			br.close();

			JSONObject jo = new JSONObject(sb.toString());
			final JSONArray jsonArray = jo.getJSONArray("data");
			HuBeiQuYuJSON = new JSONArray();
			for (int i = 0; i < jsonArray.length(); i++) {
				int depth = jsonArray.getJSONObject(i).getInt("depth");
				if (depth == 1) {
					JSONObject shen = new JSONObject();
					shen.put("id", jsonArray.getJSONObject(i).getInt("areaid"));
					shen.put("name",
							jsonArray.getJSONObject(i).getString("areaname"));
					shen.put("childs", new JSONArray());
//					System.out.println("name"
//							+ jsonArray.getJSONObject(i).getString("areaname"));
					HuBeiQuYuJSON.put(shen);
				}
			}
			for (int i = 0; i < jsonArray.length(); i++) {
				int depth = jsonArray.getJSONObject(i).getInt("depth");
				if (depth == 2) {
					JSONObject xian = new JSONObject();
					xian.put("id", jsonArray.getJSONObject(i).getInt("areaid"));
					xian.put("name",
							jsonArray.getJSONObject(i).getString("areaname"));
//					System.out.println("areaname:"
//							+ jsonArray.getJSONObject(i).getString("areaname"));
					for (int j = 0; j < HuBeiQuYuJSON.length(); j++) {
						if (HuBeiQuYuJSON.getJSONObject(j).getInt("id") == jsonArray
								.getJSONObject(i).getInt("rootid")) {
							HuBeiQuYuJSON.getJSONObject(j)
									.getJSONArray("childs").put(xian);
						}
					}
				}
			}
		}

	}

	public static void main(String[] args) throws IOException, JSONException {
		System.out.println(getReadable("星座", 1));
		System.out.println(getReadable("职业", 3));
		System.out.println(getReadable("个人资产", 3));
		getJIGUANReadable(0);
		getQUYUReadable(0);
		// readResouceFile(filename2);
	}

	static HashMap<String, String> keymap = new HashMap<String, String>();
	static {

		keymap.put("birthday", "生日");
		keymap.put("jobs", "职业");
		keymap.put("weight", "体重");
		keymap.put("education", "学历");
		keymap.put("height", "身高");
		keymap.put("interest", "兴趣");
		keymap.put("age", "年龄");
		keymap.put("housing", "居住情况");
//		keymap.put("provinceid", "籍贯");
//		keymap.put("cityid", "区域");
		keymap.put("nationcityid", "籍贯");
		keymap.put("cityid", "区域");
		keymap.put("astro", "星座");
		keymap.put("caring", "购车情况");
		keymap.put("marrystatus", "婚姻状况");

		keymap.put("endage", "年龄范围");
		keymap.put("startheight", "身高范围");
		keymap.put("startage", "年龄范围");
		keymap.put("endheight", "身高范围");
		keymap.put("areas", "区域要求");
		keymap.put("gender", "性别要求");
		keymap.put("startedu", "学历范围");
		keymap.put("avatar", "形象照");
		keymap.put("endedu", "学历范围");
		keymap.put("marry", "婚姻状况");
		keymap.put("interest", "兴趣爱好");
	}

	public static HashMap<String, KV> getUserInfo(String s)
			throws JSONException {
		JSONObject data = new JSONObject(s).getJSONArray("data").getJSONObject(
				0);

		HashMap<String, KV> mMapChine = formatUserInfo(data);
		return mMapChine;
	}

	public static HashMap<String, KV> formatUserInfo(JSONObject data) {
		HashMap<String, KV> mMapChine = new HashMap<String, KV>();
		Iterator<String> keys = data.keys();
		while (keys.hasNext()) {
			String name = keys.next();
			if ("avatar".equals(name)) {
				continue;
			}
			if ("provinceid".equals(name)) {
				continue;
			}
			final String chkey = keymap.get(name);
			if (chkey != null) {
				final String value_int = data.opt(name).toString();
				StringBuilder value = new StringBuilder();
				try {
					
					final String cs = ",";
					if (value_int.contains(cs)) {
						String[] vaInt = value_int.split(cs);
						int index = 0;
						for (String i : vaInt) {
							value.append(getReadable(chkey, Integer.parseInt(i)));
							index++;
							if (index<vaInt.length) {
								value.append(cs);
							}
						}
					}else{
						if (TextUtils.isDigitsOnly(value_int)) {
							value.append(getReadable(chkey, Integer.parseInt(value_int)));
						}else{
							value.append(value_int);
						}
						
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				KV mKV = new KV(chkey, value.toString());
				mMapChine.put(name, mKV);
			}
		}
		return mMapChine;
	}
	public static HashMap<String, KV> formatBaseInfo2HashMap(JSONObject jo) {
		String BASEINFO_DATAEXAMPLE = "生日：birthday，身高：height，体重：weight，学历：education，婚姻状况：marrystatus，职业：jobs，收入：salary，籍贯：provinceid，区域：areas，居住情况：housing，购车情况：caring，民族：national，星座：astro，个性：personality，兴趣爱好：interest";
		HashMap<String, KV> key_chinse = new HashMap<String, KV>();
		String ss[] = BASEINFO_DATAEXAMPLE.split("，");
		for (int i = 0; i < ss.length; i++) {
			String sss[] = ss[i].split("：");
			final String key = sss[1];
			String value = String.valueOf(jo.opt(key));
			final String chkey = sss[0];
			String chinese_value = "";
			if (BYQUserInfo.XUELI.equals(chkey)
					|| BYQUserInfo.HUNYINZHUNGKUANG.equals(chkey)
					|| BYQUserInfo.ZHIYE.equals(chkey)
					|| BYQUserInfo.SHOURU.equals(chkey)
					|| BYQUserInfo.JUZHUQINGKUANG.equals(chkey)
					|| BYQUserInfo.GOUCHEQINGKUANG.equals(chkey)
					|| BYQUserInfo.MINZU.equals(chkey)
					|| BYQUserInfo.XINGQU.equals(chkey)
					|| BYQUserInfo.GEXING.equals(chkey)) {
				// chinese_value = BYQUserInfo
				// .getReadableArray(chkey)[Integer
				// .parseInt(value)];
				final String value_int = value.toString();
				StringBuilder value_sb = new StringBuilder();
				try {

					final String cs = ",";
					if (value_int.contains(cs)) {
						String[] vaInt = value_int.split(cs);
						int index = 0;
						for (String s : vaInt) {
							value_sb.append(BYQUserInfo.getReadable(chkey,
									Integer.parseInt(s)));
							index++;
							if (index < vaInt.length) {
								value_sb.append(cs);
							}
						}
					}
					else {
						if (TextUtils.isDigitsOnly(value_int)) {
							value_sb.append(BYQUserInfo.getReadable(chkey,
									Integer.parseInt(value_int)));
						}else{
							value_sb.append(value_int);
						}
						
						
					}
					chinese_value = value_sb.toString();
				} catch (Exception e) {
					e.printStackTrace();
					chinese_value = "";
				}

			}
			else if (BYQUserInfo.JIGUAN.equals(chkey)) {
				value = String.valueOf(jo.opt("nationcityid"));
				if (TextUtils.isDigitsOnly(value)) {
					chinese_value = BYQUserInfo.getJIGUANReadable(Integer
							.parseInt(value));
				}
				else {
					chinese_value = "";
				}

			}
			else if (BYQUserInfo.QUYU.equals(chkey)) {
				value = String.valueOf(jo.opt("distid"));
				String value_praent = String.valueOf(jo.opt("cityid"));
				// cityid
				if (TextUtils.isDigitsOnly(value)
						&& TextUtils.isDigitsOnly(value_praent)) {
					chinese_value = BYQUserInfo.getQUYUReadable(Integer
							.parseInt(value_praent));
					chinese_value += BYQUserInfo.getQUYUReadable(Integer
							.parseInt(value));
				}
				else {
					chinese_value = "";
				}
			}
			else if (BYQUserInfo.XINGZUO.equals(chkey)) {
				if (!TextUtils.isEmpty(value)
						&& TextUtils.isDigitsOnly(value)) {
					chinese_value = BYQUserInfo.getReadable(chkey,
							Integer.parseInt(value));
				}
				else {
					chinese_value = value;
				}
			}
			else {
				chinese_value = value;
			}
//			System.out.println("chkey:" + chkey + "chinese_value:"
//					+ chinese_value);
			key_chinse.put(key, new KV(chkey, chinese_value, value, key));
		}
		return key_chinse;
	}
	public static HashMap<String, KV> getZEYOUInfo(String s)
			throws JSONException {

		String defaultuser = "{\"endage\":0,\"startheight\":0,\"startage\":0,\"endheight\":0,\"areas\":\"0\",\"gender\":\"1\",\"startedu\":0,\"avatar\":false,\"endedu\":0,\"marry\":\"1\"}";

		final JSONArray jsonArray = new JSONObject(s).getJSONArray("usercon");
		if (jsonArray.length() <= 0) {
			jsonArray.put(new JSONObject(defaultuser));
		}
		JSONObject data = jsonArray.getJSONObject(0);
		return formatZeYou(data);
	}

	public final static String ZEYOU_ConnectChar = ",";

	public static HashMap<String, KV> formatZeYou(JSONObject data) {
		HashMap<String, KV> mMapChine = new HashMap<String, KV>();
		Iterator<String> keys = data.keys();
		while (keys.hasNext()) {
			String name = keys.next();
			if ("endage".equals(name)) {
				KV mKV = new KV("年龄要求", data.optInt("startage") + "-"
						+ data.optInt("endage"), "0" + ZEYOU_ConnectChar + "0",
						"age");
				mMapChine.put(name, mKV);
				continue;
			}
			if ("endheight".equals(name)) {
				KV mKV = new KV("身高要求", data.optInt("startheight") + "-"
						+ data.optInt("endheight"), "0" + ZEYOU_ConnectChar
						+ "0", "height");
				mMapChine.put(name, mKV);
				continue;
			}
			if ("gender".equals(name)) {
				KV mKV = new KV("性别", data.optInt("gender") == 1 ? "男" : "女",
						"1", "gender");
				mMapChine.put(name, mKV);
				continue;
			}
			if ("endedu".equals(name)) {
				KV mKV = new KV("学历",
						getReadable("学历", data.optInt("startedu")) + "-"
								+ getReadable("学历", data.optInt("startedu")),
						"1" + ZEYOU_ConnectChar + "1", "education");
				mMapChine.put(name, mKV);
				continue;
			}
			if ("marry".equals(name)) {
				KV mKV = new KV("婚姻状况",
						getReadable("婚姻状况", data.optInt("婚姻状况")), "1",
						"marrystatus");
				mMapChine.put(name, mKV);
				continue;
			}
			if ("avatar".equals(name)) {
				KV mKV = new KV("形象照", data.optBoolean("avatar") ? "有" : "无",
						data.optBoolean("avatar") ? "1" : "2", "avatar");
				mMapChine.put(name, mKV);
				continue;
			}
		}
		return mMapChine;
	}

	/**
	 * 格式化身份信息
	 * 
	 * @param t
	 * @return
	 */
	public static String preFormatShenFen(String t) {

		JSONArray ja;
		try {
			final JSONObject jsonObject = new JSONObject(t);
			ja = jsonObject.getJSONArray("data");
			JSONArray newja = new JSONArray();
			for (int i = 0; i < ja.length(); i++) {
				// age/height/education/jobs
				JSONObject jo = ja.getJSONObject(i);
				String shenfen = String.format("%s岁/%scm/%s/%s",
						getReadableAge(jo.optString("age", FALLBACK)),
						jo.optInt("height", 0),
						getReadable("学历", jo.optInt("education", 0)),
						getReadable("职业", jo.optInt("jobs", 0)));
				jo.put(BYQUserInfo.KEY_SHENFEN, shenfen);

				// 状态 使用图片组合,比如 即时黄金会员又在线 这 status = 图片URL 图片内容几位两种状态的组合
				int status = getReadableStatus(jo);
				newja.put(jo);
			}
			jsonObject.put("data", newja);
			return jsonObject.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return t;
	}

	public static final String KEY_SHENFEN = "KEY_SHENFEN";
	public static final String KEY_STATUS = "KEY_STATUS";
	/**
	 * 用户组ID：1普通会员 2高级会员 3钻石会员、用户形象照
	 */
	public static final String KEY_GROUP = "KEY_GROUP";
	public static final String KEY_NEARBY = "KEY_NEARBY";
	public static final String KEY_VIP_UNIT = "KEY_VIP_UNIT";
	public static final String KEY_ONLINE = "KEY_ONLINE";
	public final static String SHOURU = "收入";
	public final static String FALLBACK = "无";

	public static String getReadableAge(String s) {
		int parseInt;
		try {
			parseInt = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			System.err.println(e.getMessage());
			return s;
		}
		return String.valueOf(parseInt);
	}

	private static HashMap<String, String[]> resMap;
	public final static String KEY_GROUPID = "groupid";
	/**
	 * 
	 * @param 返回图片路径
	 * @return
	 * @throws JSONException 
	 */
	private static int getReadableStatus(JSONObject jo) throws JSONException {
		int iconId = R.drawable.ic_vip;
//		用户组ID：1普通会员 2高级会员 3.皇冠会员 3钻石会员、用户形象照
		switch (jo.optInt(KEY_GROUPID, 1)) {
		case 1:
			iconId = R.drawable.ic_member_general;
			break;
		case 2:
			iconId = R.drawable.ic_member_crystal;
			break;
		case 3:
			iconId = R.drawable.ic_member_crown;
			break;
		case 4:
			iconId = R.drawable.ic_member_diamond;
			break;
		}
		jo.put(BYQUserInfo.KEY_GROUP, iconId);
//		jo.put(BYQUserInfo.KEY_ONLINE, status);
		if (jo.optInt("online", 0)==1) {
			jo.put(BYQUserInfo.KEY_VIP_UNIT, R.drawable.ic_vip);
		}else{
			jo.put(BYQUserInfo.KEY_VIP_UNIT,R.drawable.tran_shap12dp );
		}
		;
		return R.drawable.ic_online_phone;
	}

	private static void readResouceFile(final String filename)
			throws FileNotFoundException, IOException, JSONException {
		if (resMap == null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					BYQUserInfo.class.getResourceAsStream(filename)));
			StringBuilder sb = new StringBuilder();
			String readedLine = br.readLine();
			while (readedLine != null) {
				sb.append(readedLine);
				readedLine = br.readLine();
			}
			br.close();
			JSONObject jo = new JSONObject(sb.toString());
			final JSONArray jsonArray = jo.getJSONArray("data");
			resMap = new HashMap<String, String[]>();
			for (int i = 0; i < jsonArray.length(); i++) {
				String ptdec = jsonArray.getJSONObject(i).getString("ptdec");
				resMap.put(ptdec.split("_")[0], parseptvalue(jsonArray
						.getJSONObject(i).getString("ptvalue")));
			}
		}
	}

	public static String getReadable(String string, int i) {
		if (resMap.get(string) != null) {
			return resMap.get(string)[i];
		}
		else {
			return FALLBACK;
		}

	}

	public static String[] getReadableArray(String string) {

		return resMap.get(string);
	}

	public static String getJIGUANReadable(int id) {
		final JSONArray jsonArray = BYQUserInfo.getShenfenJSON();
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				final JSONObject jsonObject = jsonArray.getJSONObject(i);
//				System.out.println(jsonObject.getInt("id")
//						+ "name"
//						+ jsonObject.getString("name"));
				JSONArray ja = jsonObject.getJSONArray("childs");
				for (int j = 0; j < ja.length(); j++) {
					if (id == ja.getJSONObject(j).getInt("id")) {
						return ja.getJSONObject(j).getString("name");
					}
				}
				if (id == jsonObject.getInt("id")) {
					return jsonObject.getString("name");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public static String getQUYUReadable(int id) {
		final JSONArray jsonArray = BYQUserInfo.getHubeiQuYuJSON();
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				final JSONObject jsonObject = jsonArray.getJSONObject(i);
//				System.out.println("quyu"+jsonObject.getInt("id")
//						+ "name"
//						+ jsonObject.getString("name"));
				JSONArray ja = jsonObject.getJSONArray("childs");
				for (int j = 0; j < ja.length(); j++) {
					if (id == ja.getJSONObject(j).getInt("id")) {
						return ja.getJSONObject(j).getString("name");
					}
				}
				if (id == jsonObject.getInt("id")) {
					return jsonObject.getString("name");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return "";

	}

	public static String[] parseptvalue(String s) {
		String[] ss = s.split("\\|");
		String[] sss = new String[ss.length + 1];
		sss[0] = FALLBACK;
		for (int i = 0; i < ss.length; i++) {
			sss[i + 1] = ss[i].split("#")[1];
		}
		return sss;
	}

	public static CharSequence getQUYUReadable(int provinceid, int cityid) {
		return "";
	}
}
